package com.example.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.PageBean;
import com.example.entity.ProductHealth;
import com.example.entity.ProductHealthItem;
import com.example.entity.R;
import com.example.service.IProductHealthItemService;
import com.example.service.IProductHealthService;
import com.example.util.DateUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能：
 * 作者：zhuang
 * 日期：2024/6/19 10:18
 */
@RestController
@RequestMapping("/admin/productHealth")
public class AdminHealthProductController {
    @Autowired
    private IProductHealthService productHealthService;
    @Autowired
    private IProductHealthItemService productHealthItemService;


    @Value("${productHealthImagesFilePath}")
    private String productHealthImagesFilePath;

    /**
     * 根据条件分页查询
     * @param pageBean
     * @return
     */
    @RequestMapping("/list")
    public R list(@RequestBody PageBean pageBean){
        System.out.println(pageBean);
        Map<String,Object> map=new HashMap<>();
        map.put("healthName",pageBean.getQuery().trim());
        map.put("start",pageBean.getStart());
        map.put("pageSize",pageBean.getPageSize());
        List<ProductHealth> productHealthList=productHealthService.list(map);
        Long total=productHealthService.getTotal(map);
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("productHealthList",productHealthList);
        resultMap.put("total",total);
        System.out.println("productHealthList===>>>>"+productHealthList);
        return R.ok(resultMap);
    }

    /**
     * 更新是否热卖，幻灯片
     * @param id
     * @param hot
     * @return
     */
    @GetMapping("/updateHot/{id}/state/{hot}")
    public R updateHot(@PathVariable(value = "id")Integer id, @PathVariable(value = "hot")boolean hot) {
        ProductHealth productHealth = productHealthService.getById(id);
        productHealth.setIsHot(hot);
        if(hot){
            productHealth.setHotDateTime(new Date());
        }else {
            productHealth.setHotDateTime(null);
        }
        productHealthService.saveOrUpdate(productHealth);
        return R.ok();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    public R delete(@PathVariable(value = "id") Integer id){
        productHealthItemService.remove(new QueryWrapper<ProductHealthItem>().eq("healthId", id));
        productHealthService.removeById(id);
        return R.ok();
    }
    //批量删除
    @PostMapping("/deleteBatch")
    public R deleteBatch(@RequestBody List<Integer> ids) {
        for (Integer id : ids) {
            productHealthService.removeById(id);
        }
        return R.ok();
    }

    /**
     * 上传健康套餐图片
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/uploadImage")
    public Map<String,Object> uploadImage(MultipartFile file)throws Exception{
        Map<String,Object> resultMap=new HashMap<>();
        if(!file.isEmpty()){
            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            String suffixName=originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName= DateUtil.getCurrentDateStr()+suffixName;
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(productHealthImagesFilePath+newFileName));
            resultMap.put("code",0);
            resultMap.put("msg","上传成功");
            System.out.println("文件大小：" + file.getSize() + " 字节");
            Map<String,Object> dataMap=new HashMap<>();
            dataMap.put("title",newFileName);
            dataMap.put("src","/image/productImgs/"+newFileName);
            resultMap.put("data",dataMap);
        }
        return resultMap;
    }
//

    /**
     * 添加或者修改
     * @param productHealth
     * @return
     */
    @RequestMapping("/save")
    public R save(@RequestBody ProductHealth productHealth){
        if(productHealth.getId()==null || productHealth.getId()==-1){
            productHealthService.add(productHealth);

        }else{
            productHealthService.update(productHealth);
        }
        return R.ok();
    }
    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R findById(@PathVariable(value = "id")Integer id){
        ProductHealth productHealth = productHealthService.findById(id);
        Map<String,Object> map=new HashMap<>();
        map.put("productHealth",productHealth);
        return R.ok(map);
    }



    @PostMapping("/save")
    public R saveProductHealth(@RequestBody ProductHealth productHealth) {
        try {
            // 保存ProductHealth及关联的ProductHealthItems
            productHealthService.saveProductHealth(productHealth);
            return R.ok("保存成功！");
        } catch (Exception e) {
            return R.error("保存失败！");
        }
    }
}